package com.xyzwps.server.paimon.model.repository

import com.xyzwps.server.paimon.model.entity.UserSession
import com.xyzwps.server.paimon.model.table.UserSessionTable
import com.xyzwps.server.paimon.value.UserId
import org.jetbrains.exposed.v1.core.ResultRow
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.jdbc.insertAndGetId
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.jetbrains.exposed.v1.jdbc.update
import org.springframework.stereotype.Repository

internal val s = UserSessionTable

fun rowToUserSession(it: ResultRow): UserSession = UserSession(
    id = it[s.id].value,
    token = it[s.token],
    userId = UserId(it[s.userId]),
    createdAt = it[s.createdAt],
    expireTime = it[s.expireTime]
)

@Repository
class UserSessionRepository {
    fun findByToken(token: String): UserSession? =
        UserSessionTable.selectAll()
            .where { s.token eq token }
            .map { rowToUserSession(it) }
            .firstOrNull()

    fun save(userSession: UserSession): UserSession {
        if (userSession.id == null) {
            val id = UserSessionTable.insertAndGetId {
                it[token] = userSession.token
                it[userId] = userSession.userId.value
                it[createdAt] = userSession.createdAt
                it[expireTime] = userSession.expireTime
            }
            return userSession.copy(id = id.value)
        }

        UserSessionTable.update(where = { s.id eq userSession.id }) {
            it[token] = userSession.token
            it[userId] = userSession.userId.value
            it[createdAt] = userSession.createdAt
            it[expireTime] = userSession.expireTime
        }
        return userSession
    }
}
